/*
 * @Author: liuqiang
 * @Date: 2021-02-08 10:04:44
 * @Last Modified by: liuqiang
 * @Last Modified time: 2021-03-02 15:30:38
 */

/*
 * arr string[] 需要校验的字段
 * data object 请求传入的数据
 * return {
 *  err: boolean,
 *  msg: string
 * }
 */
function isRequiredParams(arr, data = {}) {
  if (!data) {
    return {
      err: true,
      msg: arr.join('、') + '是必传字段',
    };
  }
  const hasNo = [];
  arr.forEach((item) => {
    if (data[item] == undefined) {
      hasNo.push(item);
    }
  });
  if (hasNo.length !== 0) {
    return {
      err: true,
      msg: hasNo.join('、') + '是必传字段',
    };
  }
  return {
    err: false,
    msg: '',
  };
}

async function doSqlMiddle(fn = async () => {}) {
  try {
    const res = await fn();
    return res;
  } catch (err) {
    console.error(err);
    return {
      err: true,
    };
  }
}

function readFileName(path, filter = ['index.js']) {
  const fs = require('fs');
  const res = fs.readdirSync(path);
  return res.filter((item) => !filter.includes(item));
}

module.exports = {
  isRequiredParams,
  doSqlMiddle,
  readFileName,
};
